package com.mucd.chat.socket;

import com.mucd.chat.config.CustomConfigurator;
import com.mucd.chat.service.socketService.ChatSocketService;
import com.mucd.chat.service.socketService.MessageListSocketService;
import com.mucd.chat.utils.SocketUtils;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@SuppressWarnings("all")
@ServerEndpoint(value = "/websocket/messageList", configurator = CustomConfigurator.class)
@Component
@RequestMapping("ws")
@RestController
public class MessageListSocket {
    Logger logger = org.slf4j.LoggerFactory.getLogger(MessageListSocket.class);

    // WebSocket 连接打开时的操作
    @OnOpen
    public void onOpen(Session session) {

        MessageListSocketService messageListSocketServoce = SpringUtils.getBean(MessageListSocketService.class);

        SocketUtils socketUtil = SpringUtils.getBean(SocketUtils.class);
        LoginUser loginUser = socketUtil.getLoginUser(session);

        messageListSocketServoce.settingMessageListOnline(session, loginUser,true);

    }

    // WebSocket 接收到消息时的操作
    @OnMessage
    public void onMessage(Session mySession, String message, @PathParam("userId") String targetUserId) throws IOException {
        ChatSocketService chatSocketService = SpringUtils.getBean(ChatSocketService.class);

        // 获取查询参数
        SocketUtils socketUtil = SpringUtils.getBean(SocketUtils.class);
        LoginUser myLoginUser = socketUtil.getLoginUser(mySession);


        logger.info("{}已连接,userId：{}", mySession, myLoginUser.getUserId());

        chatSocketService.socketSendMessage(mySession, message, Long.valueOf(targetUserId), myLoginUser);

        logger.info("收到消息：" + message);

    }

    // WebSocket 连接关闭时的操作
    @OnClose
    public void onClose(Session session) throws IOException {
        logger.info("关闭连接：" + session);
        SocketUtils socketUtil = SpringUtils.getBean(SocketUtils.class);
        session.close();
        MessageListSocketService messageListSocketServoce = SpringUtils.getBean(MessageListSocketService.class);
        LoginUser loginUser = socketUtil.getLoginUser(session);
        messageListSocketServoce.settingMessageListOnline(session, loginUser,true);
    }

    // WebSocket 发生错误时的操作
    @OnError
    public void onError(Session session, Throwable throwable) throws IOException {
        logger.error("发生错误", throwable);
        session.getBasicRemote().sendText("发生了错误:" + throwable.getMessage());

    }
}